import java.applet.*;
import java.awt.*; // to get Graphics object.

public class WavePacket {
	// This should be two interfering sine waves
	// so we can see the difference between group velocity
	// and phase velocity.
	int height;
	int width;

	double frequency;
	double velocity;
	double timestep;  // it should know what time it is.
	double x1; // an offset for the moving long wavelength sine.

	private final double delta_t = 3.0;
	
	public WavePacket(int w, int h, double f, double v) {
		height = w; width = h; frequency = f; velocity = v;
		}
	public WavePacket(int w, int h) {
		this(w,h,12.0,1.0);
		}
	
	public void compute() {
		timestep += delta_t;
		if (timestep > 10000) {
			double frac = frequency*timestep/((double)width);
			double newtime = (width/frequency)*(frac-Math.floor(frac));
			frac = frequency*(velocity*timestep-x1)/(10.0*width);
			x1 = -(frac-Math.floor(frac))*10.0*width/frequency +
				velocity*newtime;
			timestep = newtime;
		}
	}
	public void compute( double t ) { timestep += t; }

	public void setSize( int w, int h ) { height = h; width = w; }
	
	public void setVelocity(double v) {
		x1 = x1+(velocity-v)*timestep;
		velocity = v;
	}
	public void setFrequency(double f) {
		frequency = f;
	}

	public void draw( Graphics g ) {
		int h = height; // use local copy in case it gets
		int w = width;  // altered while we draw
		double v = velocity;
		double A = ((double) h)*.45;
		double f = frequency;
		int x, x0=0,y0,y;
		double factor = 2*Math.PI*f/((double)w);
		double factor2 = 2*Math.PI*12/((double)w);
		y0 = (int) (h*.5-
			A*Math.sin(factor*(x0-timestep))*
			Math.sin(factor2*(x0-v*timestep+x1)/10));
		g.setColor(Color.red);
		for (x=0; x<w; x+=1) {
			y = (int)( (h/2)-
				A*Math.sin(factor*(x-timestep))*
				Math.sin(factor2*(x-v*timestep+x1)/10));
			g.drawLine(x0,y0,x,y);
			x0 = x;
			y0 = y;
		}
		// Here are the stupid little traveling black bars.
	/*	g.setColor(Color.black);
		int n;
		x = 0;
		n = (int)(-factor*v*timestep/Math.PI);
		while (x<w) {
			x = (int)(v*timestep+10*Math.PI*n/factor);
			g.drawLine(x,h/2-20,x,h/2);
			n+= 1;
		} */
	}
}
